<template>
  <div class="content">
    <div class="header">
      <h3 class="title">{{ contentConfig?.header?.title ?? '数据列表' }}</h3>
      <el-button type="primary" @click="handleNewUserClick" v-if="isCreate">{{
        contentConfig?.header?.btnTitle ?? '新建数据'
      }}</el-button>
    </div>

    <div class="table">
      <!-- 在el-table来设置表格要展开   v-bind="contentConfig.childrenTree" -->
      <el-table
        :data="props.contentConfig.pageName === 'store' ? storeList : pageList"
        border
        style="width: 100%"
        v-bind="contentConfig.childrenTree"
      >
        <template v-for="item in contentConfig.propsList" :key="item.prop">
          <template v-if="item.type === 'timer'">
            <el-table-column align="center" v-bind="item">
              <template #default="scope">
                {{ formatUTC(scope.row[item.prop]) }}
              </template>
            </el-table-column>
          </template>

          <template v-else-if="item.type === 'fuContent'">
            <el-table-column align="center" v-bind="item">
              <template #default="scope"> <div v-html="scope.row[item.prop]"></div> </template>
            </el-table-column>
          </template>

          <template v-else-if="item.type === 'handler'">
            <el-table-column align="center" :label="item.label" :width="item.width">
              <template #default="scope">
                <el-button
                  size="small"
                  icon="Edit"
                  type="primary"
                  text
                  @click="handleEditBtnClick(scope.row)"
                  v-if="isUpdate"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  icon="Delete"
                  type="danger"
                  text
                  @click="handleDeleteBtnClick(scope.row.id)"
                  v-if="isDelete"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>

          <!-- 通过作用域插条定制内容，作用域插条上面的属性全添加到了scope上面,另外一个地方用这个插条时通过scope拿到数据, -->
          <!-- v-bind="item" 可以把item的属性全部动态绑定，而不需要一个一个绑定-->
          <template v-else-if="item.type === 'custom'">
            <el-table-column align="center" v-bind="item">
              <template #default="scope">
                <slot :name="item.slotName" v-bind="scope" :prop="item.prop" hName="峰锅"> </slot>
              </template>
            </el-table-column>
          </template>

          <template v-else>
            <el-table-column align="center" v-bind="item"></el-table-column>
          </template>
        </template>
      </el-table>
    </div>

    <!-- 确认框  -->
    <div>
      <el-dialog v-model="dialogVisible" title="删除提示" width="30%">
        <span>您确定要删除该数据吗？</span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleCancelBtnClick()" style="margin-right: 10px">取消</el-button>
            <el-button type="primary" @click="handleOkBtnClick()"> 确定 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30]"
        layout="total,sizes,prev,pager,next,jumper"
        :total="props.contentConfig.pageName === 'store' ? storeTotalCount : pageTotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia'
import useSystemStore from '@/store/main/system/system'
import { formatUTC } from '@/utils/format'
import { ref } from 'vue'
import userPermissions from '@/hooks/usePermissions'
import useStoreStore from '@/store/main/store/store'

const currentPage = ref(1)
const pageSize = ref(10)

interface IProps {
  contentConfig: {
    pageName: string
    header?: {
      title?: string
      btnTitle?: string
    }
    propsList: any[]
    childrenTree?: {}
  }
}

const props = defineProps<IProps>()

// 定义事件
const emit = defineEmits(['newClick', 'editClick'])

// 获取是否有对应的增删改查权限
const isCreate = userPermissions(`${props.contentConfig.pageName}:create`)
const isDelete = userPermissions(`${props.contentConfig.pageName}:delete`)
const isUpdate = userPermissions(`${props.contentConfig.pageName}:update`)
let isQuery = userPermissions(`${props.contentConfig.pageName}:query`)

// 1.发起action，请求pagesList的数据
const systemStore = useSystemStore()

const storeStore = useStoreStore()
storeStore.postStoreListAction()

fetchPageListData()

// // 监听pinia中的action被调用
// systemStore.$onAction((args1) => {
//   // console.log(args1)
//   args1.after(() => {
//     if (
//       args1.name === 'deletePageByIdAction' ||
//       args1.name === 'editPageDataAction' ||
//       args1.name === 'newPageDataAction'
//     ) {
//       currentPage.value = 1
//     }
//   })
// })

// name是当前调用的action方法,after是一个回调函数,当action方法执行完毕且执行成功的时候,after函数里面的内容才会执行
// 为了保证完美还是要用after，不太严格的话不用的话也行
systemStore.$onAction(({ name, after }) => {
  after(() => {
    // console.log(name)
    if (
      name === 'deletePageByIdAction' ||
      name === 'editPageDataAction' ||
      name === 'newPageDataAction'
    ) {
      currentPage.value = 1
    }
  })
})

// 2.获取pagesList数据,进行展示
const { pageList, pageTotalCount } = storeToRefs(systemStore)
const { storeList, storeTotalCount } = storeToRefs(storeStore)

// 页码相关的逻辑
function handleSizeChange() {
  // console.log('page-size-change', pageSize.value)
  fetchPageListData()
}
function handleCurrentChange() {
  // console.log('current-page-change', currentPage.value)
  fetchPageListData()
}

// 定义函数，用于发送网络请求
function fetchPageListData(formData: any = {}) {
  if (props.contentConfig.pageName === 'store') {
    isQuery = true
  }
  if (!isQuery) return
  // 获取offset和size
  const size = pageSize.value
  const offset = (currentPage.value - 1) * size
  const info = { size, offset }
  const queryInfo = { ...info, ...formData }
  // console.log(props.contentConfig.pageName)
  if (props.contentConfig.pageName === 'store') {
    storeStore.postStoreListAction(info)
  } else {
    systemStore.postPageListAction(props.contentConfig.pageName, queryInfo)
  }
}

// 确认框弹出或关闭
const dialogVisible = ref(false)

// 处理删除功能
let deleteId = 0
function handleDeleteBtnClick(id) {
  dialogVisible.value = true
  deleteId = id
}

// 确认框确定操作
function handleOkBtnClick() {
  systemStore
    .deletePageByIdAction(props.contentConfig.pageName, deleteId)
    .then((res) => {
      if (res !== -1002) {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
      } else {
        ElMessage({
          message: '删除失败，请稍后重试',
          type: 'warning'
        })
      }
    })
    .catch((err) => {
      ElMessage({
        message: '删除失败，请稍后重试',
        type: 'warning'
      })
    })
  dialogVisible.value = false
  currentPage.value = 1
}

// 确认框取消操作
function handleCancelBtnClick() {
  dialogVisible.value = false
}

// 新建用户的操作
function handleNewUserClick() {
  emit('newClick')
}

// 处理编辑事务
function handleEditBtnClick(itemData) {
  emit('editClick', itemData)
}

// 将fetchPageListData方法暴露出去，才能通过组件ref.value查到
defineExpose({ fetchPageListData })
</script>

<style lang="less" scoped>
.content {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 10px;

  .title {
    font-size: 22px;
  }
}

.table {
  :deep(.el-table__cell) {
    padding: 12px 0;
  }

  .el-button {
    margin-left: 0;
    padding: 5px 8px;
  }
}
.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 0 0;
}
</style>
@/hooks/usePermissions
